<template>
    <div>
        <!--        面包屑-->
        <!--        <el-breadcrumb separator="/" style="padding-left: 10px;padding-bottom: 10px;font-size: 12px">-->
        <!--            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>-->
        <!--            <el-breadcrumb-item>考试管理</el-breadcrumb-item>-->
        <!--        </el-breadcrumb>-->
        <!--        用户列表卡片-->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="科目" label-width="70px" prop="source">
                <el-input clearable v-model="formInline.source" placeholder="请输入科目"></el-input>
            </el-form-item>
            <el-form-item label="班级" label-width="70px" prop="source">
                <el-input clearable v-model="formInline.className" placeholder="请输入班级"></el-input>
            </el-form-item>
            <el-form-item label="年级" label-width="70px" prop="grade">
                <el-input clearable v-model="formInline.grade" placeholder="请输入年级"></el-input>
            </el-form-item>
            <el-form-item label-width="70px" prop="enable">
                <el-radio v-model="formInline.enable" label="1">进行</el-radio>
                <el-radio v-model="formInline.enable" label="0">结束</el-radio>
                <el-radio v-model="formInline.enable" label="">全部</el-radio>
            </el-form-item>
            <el-form-item label="描述" label-width="70px" prop="description">
                <el-input clearable v-model="formInline.description" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 10px">
                <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
                <el-button @click="selectExam" type="primary" icon="el-icon-search">查询</el-button>
                <el-button type="success" icon="el-icon-plus" @click="showAddExam">添加</el-button>
                <el-button type="warning" icon="el-icon-download">导出</el-button>
            </el-form-item>
        </el-form>
        <el-checkbox-group v-model="checkArr" size="medium">
            <el-col :span=4 v-for="item in optionalColumnList" :key="item.prop">
                <el-checkbox :label="item.propName" @change="menuChange(item)"></el-checkbox>
            </el-col>
        </el-checkbox-group>
        <el-table border
                  style="width: 100%"
                  ref="multipleTable"
                  :data="tableData">
            <el-table-column :label="item.propName" :property="item.prop" v-for="(item) in tableColumnList"
                             :key="item.prop" sortable>
                <template slot-scope="scope">
                    <span v-if="item.propName==='考试标题'||item.propName==='班级'"><el-tag>{{scope.row[scope.column.property]}}</el-tag></span>
                    <span v-else-if="item.propName==='是否禁用'">
                                            <el-switch v-model="scope.row.enable"
                                                       :active-value="1"
                                                       :inactive-value="0"
                                                       active-color="#13ce66"
                                                       inactive-color="#ff4949"
                                                       @change=chang(scope.row)
                                            >
                                            </el-switch>
                                        </span>
                    <span v-else>{{scope.row[scope.column.property]}}</span>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="175px">
                <template slot-scope="scope">
                    <el-button @click="showUploadExam(scope.row)" type="primary" size="mini"
                               icon="el-icon-upload2"></el-button>
                    <el-button @click="scoreView(scope.row)" type="warning" size="mini"
                               icon="el-icon-s-data"></el-button>
                    <el-button @click="showEditExam(scope.row)" type="danger" size="mini"
                               icon="el-icon-edit"></el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="padding-top: 15px"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="current"
                       :page-sizes="[1, 2, 3, 6, 15]"
                       :page-size="size"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="this.total">
        </el-pagination>

        <el-dialog
                title="编辑考试"
                :visible.sync="dialogVisible"
                width="30%">
            <div>
                <el-form ref="form" :model="updateTableData" label-width="80px">
                    <el-form-item label="考试标题">
                        <el-input v-model="updateTableData.description" placeholder="请输入考试标题" class="input-with-select">
                            <el-select v-model="updateTableData.source" slot="prepend" placeholder="科目"  @change="curRowCanClass">
                                <el-col v-for="item in curRowCanSourceData" :key="item">
                                    <el-option :label="item" :value="item"></el-option>
                                </el-col>
                            </el-select>
                        </el-input>
                    </el-form-item>

                    <el-form-item label="考试时间">
                        <el-date-picker v-model="updateTableData.examDate" size="small" type="datetime"
                                        placeholder="请输入开始时间"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="基本属性">
                        <el-col :span="10">
                            <el-input v-model="updateTableData.totalTime" placeholder="请输入时长"></el-input>
                        </el-col>

                        <el-col :span="2">分钟</el-col>
                        <el-col :span="10">
                            <el-input v-model="updateTableData.totalScore" placeholder="请输入总分"></el-input>
                        </el-col>
                        <el-col :span="2">分</el-col>
                    </el-form-item>
                    <el-form-item label="注意事项">
                        <el-input type="textarea" v-model="updateTableData.tips"></el-input>
                    </el-form-item>

                    <el-form-item label="可看程度">
                        <el-radio-group v-model="updateTableData.can">
                            <el-radio :label="0">仅自己可看</el-radio>
                            <el-radio :label="1">班级可看</el-radio>
                            <el-radio :label="2">课程可看</el-radio>
                            <el-radio :label="4">全部可看</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-collapse v-model="updateTableData.can">
                        <el-collapse-item title="班级可见" :name="1">
                            <el-form-item label="可选班级">
                                <el-checkbox-group v-model="updateTableData.classNameArr" size="medium">
                                    <el-col v-for="item in curRowCanClassData" :key="item">
                                        <el-checkbox :label="item"></el-checkbox>
                                    </el-col>
                                </el-checkbox-group>
                            </el-form-item>
                        </el-collapse-item>
                        <el-collapse-item title="课程可看" :name="2">
                            <el-form-item label="课程">
                                <el-select v-model="updateTableData.source" placeholder="请选择发布的课程">
                                    <el-col v-for="item in curRowCanSourceData" :key="item">
                                        <el-option :label="item" :value="item"></el-option>
                                    </el-col>
                                </el-select>
                            </el-form-item>
                        </el-collapse-item>
<!--                        <el-collapse-item title="全部可看" :name="4">-->
<!--                            <el-form-item label="课程">-->
<!--                                <el-select v-model="updateTableData.grade" placeholder="请选择可看的年级">-->
<!--                                    <el-option label="2019级" value="2019"></el-option>-->
<!--                                    <el-option label="2020级" value="2020"></el-option>-->
<!--                                </el-select>-->
<!--                            </el-form-item>-->
<!--                        </el-collapse-item>-->
                    </el-collapse>
                </el-form>
                <!--                <div><el-tag>科目</el-tag><el-input v-model="updateTableData.source" size="small" class="updatePosInput" placeholder="请输入科目"></el-input></div><div>-->
                <!--                <el-tag type="success" style="margin: 0 8px 0 0">*开始时间</el-tag><el-date-picker v-model="updateTableData.examDate" size="small" type="datetime" placeholder="请输入开始时间"></el-date-picker></div><div>-->
                <!--                <el-tag type="info">*时长</el-tag><el-input v-model="updateTableData.totalTime" size="small" class="updatePosInput" placeholder="请输入时长"></el-input></div><div>-->
                <!--                <el-tag type="warning">*总分</el-tag><el-input v-model="updateTableData.totalScore" size="small" class="updatePosInput" placeholder="请输入总分"></el-input></div><div>-->
                <!--                <el-tag type="danger">*说明</el-tag><el-input v-model="updateTableData.description" size="small" class="updatePosInput" placeholder="请输入说明"></el-input></div><div>-->
                <!--                <el-tag>年级</el-tag><el-input v-model="updateTableData.grade" size="small" class="updatePosInput" placeholder="请输入年级"></el-input></div><div>-->
                <!--                <el-tag type="success">班级</el-tag><el-input v-model="updateTableData.className" size="small" class="updatePosInput" placeholder="请输入班级"></el-input></div><div>-->
                <!--                <el-tag type="info">专业</el-tag><el-input v-model="updateTableData.major" size="small" class="updatePosInput" placeholder="请输入专业"></el-input></div><div>-->
                <!--                <el-tag type="warning">学院</el-tag><el-input v-model="updateTableData.institute" size="small" class="updatePosInput" placeholder="请输入学院"></el-input></div><div>-->
                <!--                <el-tag type="info">分配试卷码</el-tag><el-input v-model="updateTableData.paperId" size="small" class="updatePosInput" placeholder="请输入试卷码"></el-input></div><div>-->
                <!--                <el-tag type="danger">注意事项</el-tag><el-input v-model="updateTableData.tips" size="small" class="updatePosInput" placeholder="请输入注意事项"></el-input></div>-->
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateOrInsertExam">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="上传考卷"
                   :visible.sync="autoExamVisible"
                   width="30%">
            <el-upload
                    class="upload-demo"
                    multiple
                    :file-list="fileList"
                    show-file-list
                    list-type="picture"
                    :headers="{ 'Authorization': tokenStr }"
                    :before-upload="beforeAvatarUpload" action="">
                <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="autoExamVisible = false">取 消</el-button>
                <el-button @click="pushDeriveExcelManage">管 理</el-button>
                <el-button type="primary" @click="upload">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

    export default {
        name: "TeacherExamManage",
        components: {},
        methods: {
            pushDeriveExcelManage() {
                // 进行页面跳转至ExcelManage页面
                // this.$router.replace('/teacher/TeacherDeriveExcelManage');
                this.$router.push({
                    path: "/teacher/TeacherDeriveExcelManage",
                    query: {examId: this.currentExamId}
                });
            },
            beforeAvatarUpload(file) {
                let test = file.name.substring(file.name.lastIndexOf(".") + 1);
                const extension =
                    test === "jpg" ||
                    test === "JPG" ||
                    test === "png" ||
                    test === "PNG" ||
                    test === "bpm" ||
                    test === "BPM";
                const isLt50M = file.size / 1024 / 1024 < 10;
                if (!extension) {
                    this.$message({
                        message: "上传图片只能是jpg / png / bpm格式!",
                        type: "error"
                    });
                    return false; //必须加上return false; 才能阻止
                }
                // console.log(file);
                if (!isLt50M) {
                    this.$message({
                        message: "上传文件大小不能超过 10MB!",
                        type: "error"
                    });
                    return false;
                }
                this.fileList.push(file);
                return extension || isLt50M;
            },
            upload() {
                console.log(this.fileList.length);
                for (let i = 0; i < this.fileList.length; i++) {
                    this.formData.append("pictures", this.fileList[i]);
                    console.log(this.fileList[i]);
                }
                console.log(this.currentExamId);
                this.postRequest('/Oss/uploadImgFileList/' + this.currentExamId, this.formData, {headers: {'Content-Type': 'multipart/form-data'}}).then(resp => {
                    this.$message(this.currentExamId);
                    this.$message(this.formData);
                    if (resp) {
                        this.dialogVisible = false;
                        this.$message(resp.data.message);
                        this.fileList = [];
                    } else {
                        this.$message("失败了");
                    }
                })
                this.autoExamVisible = false;
            },
            scoreView(row) {
                // 进行页面跳转至成绩视图页面
                this.$router.push({
                    path: "/teacher/TeacherScoreView",
                    query: {examRow: row}
                });
            },
            showAddExam() {
                this.dialogVisible = true;
                // this.updateTableData = '';
                this.updateTableData = { //初始化
                    "source": "",
                    "examDate": "",
                    "totalTime": "",
                    "totalScore": "",
                    "enable": "",
                    "description": "",
                    "grade": "",
                    "className": "",
                    "major": "",
                    "institute": "",
                    "paperId": "",
                    "tips": "",
                    "can": "",
                    "createId": "",
                    classNameArr: [],
                }
            },
            curRowCanClass() {
                // 清空选择残留
                this.updateTableData.classNameArr = [];
                // 查看当前用户所教授的全部班级
                this.getRequest('/courseDistribution/selectClassName/'+this.username+'/'+this.updateTableData.source).then(resp => {
                    if (resp) {
                        this.curRowCanClassData = resp.data;
                        console.log(resp.data);
                    }
                })
            },
            curRowCanSource() {
                // 查看当前用户能教授的全部课程
                this.getRequest('/courseDistribution/selectCourseName/'+this.username).then(resp => {
                    if (resp) {
                        this.curRowCanSourceData = resp.data;
                        // console.log(resp.data);
                    }
                })
            },
            updateOrInsertExam() {
                let str = "";
                for (let i = 0; i < this.updateTableData.classNameArr.length; i++) {
                    if (i != this.updateTableData.classNameArr.length - 1) {
                        str = str + this.updateTableData.classNameArr[i] + ",";
                    } else {
                        str = str + this.updateTableData.classNameArr[i];
                    }
                }
                this.updateTableData.className = str;
                this.updateTableData.createId = this.username;
                this.updateTableData.enable = 1;
                var json_date = new Date(this.updateTableData.examDate).toJSON();
                this.updateTableData.examDate=new Date(new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
                // if(this.updateTableData.can == 2){
                //     // 如果是课程可见那么就自动填充classname字段为课程下的全部班级
                //     this.getRequest('/courseDistribution/selectClassNameByCourseName/'+this.updateTableData.source).then(resp => {
                //         // 看一下返回信息
                //         // alert(JSON.stringify(resp));
                //         if (resp) {
                //             this.updateTableData.className = resp.data;
                //         }
                //     })
                // }
                this.postRequest('/exam/updateOrInsertExam',this.updateTableData).then(resp => {
                    // 看一下返回信息
                    // alert(JSON.stringify(resp));

                    if (resp) {
                        this.selectExam();
                        this.dialogVisible = false;
                    }
                })
            },
            showEditExam(row) {
                Object.assign(this.updateTableData, row);// 注意日期的格式
                console.log(this.updateTableData);
                this.dialogVisible = true;
            },
            selectExam() {
                this.postRequest('/exam/teacherSelectExam/' + this.current + '/' + this.size, this.formInline).then(resp => {
                    // 看一下返回信息
                    console.log(this.formInline);
                    // alert(JSON.stringify(resp));
                    if (resp) {
                        this.tableData = resp.data.records;
                        this.total = resp.data.total;
                    }
                })
            },
            showUploadExam(row) {
                console.log("row:->" + row.id);
                this.currentExamId = row.id;

                // Object.assign(this.updateTableData,row);// 注意日期的格式
                this.autoExamVisible = true;
            },
            chang(row) {
                // const _this = this;
                console.log(row.id);
                this.putRequest('/exam/updateEnable', 'id=' + row.id + '&' + 'enable=' + row.enable).then(resp => {
                    if (resp) {
                        console.log(resp);
                        this.$message(resp.data.message)
                    } else {
                        this.$message('失败')
                    }
                })
            },
            // 分页改变每页数量
            handleSizeChange(size) {
                this.size = size;
                this.selectExam();
            },
            // 分页改变当前页数
            handleCurrentChange(current) {
                this.current = current;
                this.selectExam();
            },
            // 动态表头
            menuChange(item) {
                // 注意  我这里都用的假数据，要从后台获取tableColumnList和dataList的时候
                //，每一次调用menuChange都要重新获取tableColumnList和dataList，保证属性和数据是对应的
                let flag = true
                for (let i = 0; i < this.checkArr.length; i++) {
                    if (this.checkArr[i] === item.propName) {
                        flag = false
                        break
                    }
                }
                if (!flag) {
                    this.tableColumnList.push(item)
                }
                if (flag) {
                    Array.prototype.contains = function (obj) {
                        let j = this.length;
                        while (j--) {
                            if (this[j] === obj) {
                                return j; // 返回的这个 i 就是元素的索引下标，
                            }
                        }
                        return false
                    }
                    this.tableColumnList.splice(this.tableColumnList.contains(item), 1)
                }
            },
            reset() {
                this.formInline.source = null;
                this.formInline.grade = null;
                this.formInline.className = null;
                this.formInline.enable = null;
                this.formInline.description = null;
                this.selectExam();
            },
        },
        created() {
            this.selectExam();
            this.curRowCanSource();
        },
        data() {
            return {
                tokenStr: localStorage.getItem('tokenStr'),
                formData: new FormData(),
                fileList: [],
                // 分页
                size: 6,
                current: 1,
                total: 0,
                dialogVisible: false, // 编辑弹出框显示控制
                autoExamVisible: false, // 编辑弹出框显示控制
                updateTableData: {
                    "source": "",
                    "examDate": "",
                    "totalTime": "",
                    "totalScore": "",
                    "enable": "",
                    "description": "",
                    "grade": "",
                    "className": "",
                    "major": "",
                    "institute": "",
                    "paperId": "",
                    "tips": "",
                    "can": "",
                    "createId": "",
                    classNameArr: [],
                },
                canClass: ['卓越191', 'RB软工数191'],// 能教授的班级
                tableData: null,
                tableColumnList:
                    [
                        {prop: 'description', propName: '考试标题'},
                        {prop: 'source', propName: '科目'},
                        {prop: 'examDate', propName: '开始时间'},
                        {prop: 'totalTime', propName: '共时长'},
                        {prop: 'totalScore', propName: '总分'},
                        {prop: 'enable', propName: '是否禁用'},
                    ],
                optionalColumnList:
                    [
                        {prop: 'grade', propName: '年级'},
                        {prop: 'className', propName: '班级'},
                        {prop: 'major', propName: '专业'},
                        {prop: 'institute', propName: '学院'},
                        {prop: 'tips', propName: '注意事项'},
                    ],
                checkArr: [],
                formInline: {
                    "source": null,
                    "grade": null,
                    "className": null,
                    "enable": null,
                    "description": null,
                    "createId" : JSON.parse(window.sessionStorage.getItem('user')).username
                },
                currentExamId: 0, // 存储当前行数据
                username: JSON.parse(window.sessionStorage.getItem('user')).username,
                curRowCanSourceData: null,
                curRowCanClassData: null,
            }
        }
    }
</script>
<style>
    .el-select .el-input {
        width: 130px;
    }

    .input-with-select .el-input-group__prepend {
        background-color: #fff;
    }

    .updatePosInput {
        width: 180px;
        margin: 8px;
    }
</style>